package com.apes.fn.scm.commodityInquiry.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.mdm.purchase.PurchasingGroup;
import com.apes.fn.mdm.purchase.PurchasingGroupRepository;
import com.apes.fn.pi.fnCommunal.FnCommunalService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.repository.PostRepository;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * 构建数据
 * Created by lishikun on 2021/7/1 22:01
 */

@Service("buildCommodityDataService")
public class BuildCommodityData {
    @Autowired
    private EnumerationRepository enumerationRepository;

    public static BuildCommodityData createBuildCommodityData() {
        return new BuildCommodityData();
    }

    // 构建询价池数据
    public Map buildInquiryPool(Map collect, Map cache, String ID, String platform, SimpleRequest request) {
        List inquiryPoolList = new ArrayList();
        JSONObject jo = request.getJO();
        Set<String> keySet = collect.keySet();
        String CPHM = "", PZCXID = "", PZCXMC = "", QCPPMC = "", QCCPMC = "";
        Post post = null;
        if (StringUtils.hasText(request.getPostId()) && "fn".equals(jo.getString("platform"))){
            post = SpringManager.getBean(PostRepository.class).findOne(request.getPostId());
        }
        for (String s : keySet) {
            List<Object> objects = (List<Object>) collect.get(s);
            Post finalPost = post;
            List<JSONObject> list = objects.stream().map(o -> {
                JSONObject oldInquiry = (JSONObject) o;
                int iHYZT = oldInquiry.getInteger("HYZT");
                String gysid = oldInquiry.getString("GYSID");
                String gysmc = oldInquiry.getString("GYSMC");
                String wyz = oldInquiry.getString("WYZ");
                String xjdh = oldInquiry.getString("XJDH");
                String zdmc =  oldInquiry.getString("ZDMC");
                int yjdhsc = oldInquiry.getIntValue("YJDHSC");
                String yspid = oldInquiry.getString("YSPID");
                String logisticsMode = oldInquiry.getString("logisticsMode");
                oldInquiry.put("supplier", getSupplier(cache, gysid, ID, platform));
                oldInquiry.put("HYMC", iHYZT == 0?"无货":iHYZT == 1?"现货":"需订货");
                JSONArray documentDetails = jo.getJSONArray("servicePlanItems") == null?jo.getJSONArray("lossQuotationItems"):jo.getJSONArray("servicePlanItems");
                documentDetails = documentDetails == null?new JSONArray():documentDetails;
                oldInquiry.putAll(this.obtainLogisticsMoed(oldInquiry.getString("CGZID"), gysmc, logisticsMode, wyz, documentDetails));
                oldInquiry.putAll(this.appendOriginalData(yspid, documentDetails));
                if (StringUtils.hasText(logisticsMode)) logisticsMode = oldInquiry.getJSONObject("logisticsMode").isEmpty()?"":oldInquiry.getJSONObject("logisticsMode").getString("id");

                String deliveryPlace = this.obtainDeliveryPlace(gysid, wyz, xjdh, oldInquiry.getString("DELIVERY_PLACE"));
                oldInquiry.put("deliveryPlace", deliveryPlace);
                oldInquiry.put("EXTERNAL_GYSID", "00004465".equals(gysid)?"00004465":oldInquiry.getString("EXTERNAL_GYSID"));
                oldInquiry.put("MDID", oldInquiry.getString("MDID"));
                oldInquiry.put("THIRD_SUPPLIER_PICTURES", oldInquiry.getString("THIRD_SUPPLIER_PICTURES"));

                if (finalPost != null && !"001073".equals(finalPost.getOperation())) oldInquiry.put("operation", finalPost.getOperation());

                // 获取到达时间
                String purchaseInformation = this.purchaseInformation(yjdhsc, zdmc, gysmc, logisticsMode, iHYZT);
                oldInquiry.put("purchaseInformation", purchaseInformation);

                return oldInquiry;
            }).sorted(Comparator.comparing(e ->
            {JSONObject json = (JSONObject)e; return json.getString("XFPZID");},
                    Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());
            Map objectsM = (Map) objects.get(0);
            CPHM = this.paramValue(objectsM, "CPHM");
            PZCXID = this.paramValue(objectsM, "PZCXID");
            PZCXMC = this.paramValue(objectsM, "PZCXMC");
            QCPPMC = this.paramValue(objectsM, "QCPPMC");
            QCCPMC = this.paramValue(objectsM, "QCCPMC");

            inquiryPoolList.add(MapUtil.mapper("YSPID", objectsM.get("YSPID"),
                    "YSPMC", objectsM.get("YSPMC"),
                    "id", objectsM.get("YSPID"),
                    "name", objectsM.get("YSPMC"),
                    "YPJMC", objectsM.get("YPJMC"),
                    "YPJMCID", objectsM.get("YPJMCID"),
                    "item", list));
        }
        if ("123".equals(platform)) {
            return  MapUtil.mapper("item",inquiryPoolList,
                    "CPHM", CPHM,
                    "QCCPMC", QCCPMC,
                    "QCPPMC", QCPPMC,
                    "PZCXID", PZCXID,
                    "PZCXMC", PZCXMC);
        } else {
            return  MapUtil.mapper("item",inquiryPoolList,
                    "CPHM", CPHM,
                    "PZCXID", PZCXID,
                    "PZCXMC", PZCXMC);
        }

    }

    // 必须要返回的明细数据
    private Map appendOriginalData(String yspid, JSONArray documentDetails) {
        for (int i = 0, iLen = documentDetails.size(); i < iLen; i++) {
            JSONObject documentDetail = documentDetails.getJSONObject(i);
            JSONObject product = documentDetail.getJSONObject("product");
            double platformPriceCosInTax = documentDetail.getDoubleValue("platformPriceCosInTax");
            if (yspid.equals(product.get("id")) && platformPriceCosInTax == 0) {
                return MapUtil.mapper("partCode", documentDetail.get("partCode"), "partName", documentDetail.get("partName"), "tagMapAddress", documentDetail.get("tagMapAddress"), "originalInquiryProduct", product);
            }
        }
        return new HashMap();
    }

    private String purchaseInformation(int yjdhsc, String zdmc, String gysmc, String logisticsModeId, int iHYZT) {
        if ("广东三头六臂信息科技有限公司(经销)服务站".contains(gysmc)) return "";
        if ("002085".equals(logisticsModeId) || "002087".equals(logisticsModeId) || gysmc.indexOf("外采") != -1) return "";

        if (gysmc.contains("巴图鲁") && iHYZT == 1) {
            return iHYZT == 1?"11:00 前下单，14:00 前发货\r\n18:00 前下单，21:00 前发货":"";
        }
        try {
            int days = yjdhsc / 24;
            int hours = yjdhsc % 24;
            String showTime = "";
            if (days != 0 && hours != 0) showTime = days + "天" + hours + "小时";
            if (days != 0 && hours == 0) showTime = days + "天";
            if (days == 0 && hours != 0) showTime = hours + "小时";
            return "下单后" + showTime + "送达" + zdmc;
        } catch (Exception e) {
        }
        return "";
    }

    // 获取发货地
    private String obtainDeliveryPlace(String supplierId, String wyz, String xjdh, String originDeliveryPlace) {
        // 不等于巴图鲁
        if (supplierId.length() == 8) supplierId = supplierId.substring(2, supplierId.length());
        PartyRole supplier = SpringManager.getBean(PartyRoleRepository.class).findOne(supplierId);
        if (Objects.isNull(supplier)) return "";

        if ("004465".equals(supplier.getId())) return "";
        if ("006989".equals(supplier.getId())) return "";
        if (supplier.getParty().getName().indexOf("巴图鲁") > -1 || StringUtils.hasText(originDeliveryPlace)) return originDeliveryPlace;

        if (ObjectUtils.isEmpty(supplier)) return "";
        Area officeCounty = supplier.getParty().getCorporate().getOfficeCounty();
        Area city = SpringManager.getBean(AreaRepository.class).findOne(officeCounty.getParent());
        String deliveryPlace = city.getName() + "/" + officeCounty.getName();
        JSONObject condi = new JSONObject(MapUtil.mapper("XJDH", xjdh, "WYZ", wyz, "DELIVERY_PLACE", deliveryPlace));
        SpringManager.getBean(PiManager.class).synErp("scmGysxjdService.updateSPXJDZXBAddress", condi);
        return city.getName() + "/" + officeCounty.getName();
    }

    private String paramValue(Map objectsM, String column) {
        if (ObjectUtils.isEmpty(objectsM)) return "";
        return ObjectUtils.isEmpty(objectsM.get(column))?"":objectsM.get(column).toString();
    }

    // 询价处理 - 获取物流方式
    private JSONObject obtainLogisticsMoed(String cgzid, String gysmc, String logisticsMode, String wyz, JSONArray servicePlanItems) {
        JSONObject returnData = new JSONObject();
        Enumeration logisticsMoed = null;
        JSONObject logisticsModeData;

        if (gysmc.indexOf("巴图鲁") != -1) {
            Enumeration enumeration = SpringManager.getBean(EnumerationRepository.class).findByTypeAndCode("logisticsMode", "merchant");
            returnData.putAll(MapUtil.mapper("logisticsMode", MapUtil.mapper("id", enumeration.getId(), "name", enumeration.getDescription())));
            return returnData;
        }

        //三头六臂供应商物流方式为商家配送
        if ("广东三头六臂信息科技有限公司(经销)服务站".equals(gysmc)){
            logisticsMoed = SpringManager.getBean(EnumerationRepository.class).findOne("S006541");
            logisticsModeData = new JSONObject();
            logisticsModeData.put("id", logisticsMoed.getId());
            logisticsModeData.put("name", logisticsMoed.getDescription());
            returnData.put("logisticsMode", logisticsModeData);
            return returnData;
        }
        if (gysmc.indexOf("现金外采") != -1) {
            returnData.put("logisticsMode", MapUtil.mapper("id", "--", "name", "--"));
            return returnData;
        }

        // 将已选择的承运方式匹配到现有数据
        if (StringUtils.isEmpty(logisticsMode) && servicePlanItems != null) {
            JSONObject getlogisticsMode = servicePlanItems.stream().map(servicePlanItem -> {
                Map servicePlanItemObj = (Map) servicePlanItem;
                if (wyz.equals(servicePlanItemObj.get("uniqueValue"))) {
                    JSONObject appendLogisticsModeData = new JSONObject();
                    appendLogisticsModeData.put("id", servicePlanItemObj.get("carrierId"));
                    appendLogisticsModeData.put("name", servicePlanItemObj.get("carrierName"));
                    return appendLogisticsModeData;
                } else {
                    return returnData;
                }
            }).filter(carrierInfo -> !carrierInfo.isEmpty()).findFirst().orElse(new JSONObject());
            if (!getlogisticsMode.isEmpty()) {
                returnData.put("logisticsMode", getlogisticsMode);
                return returnData;
            }
        }
        if (StringUtils.isEmpty(cgzid)) return returnData;

        PurchasingGroup pGroup = SpringManager.getBean(PurchasingGroupRepository.class).findOne(cgzid);
        if (Objects.isNull(pGroup)) return returnData;
        if (pGroup.isVirtual()) {
            logisticsMoed = SpringManager.getBean(EnumerationRepository.class).findOne("002085"); // 正式库必须编码一致
            logisticsModeData = new JSONObject();
            logisticsModeData.put("id", logisticsMoed.getId());
            logisticsModeData.put("name", logisticsMoed.getDescription());
            returnData.put("logisticsMode", logisticsModeData);
            return returnData;
        } else {
            logisticsMoed = SpringManager.getBean(EnumerationRepository.class).findOne("002086");
            logisticsModeData = new JSONObject();
            logisticsModeData.put("id", logisticsMoed.getId());
            logisticsModeData.put("name", logisticsMoed.getDescription());
            returnData.put("logisticsMode", logisticsModeData);
            return returnData;
        }
    }

    // 供应商
    private Object getSupplier(Map map, String supplier, String ID, String platform) {
        return getRealSupplier(map, supplier, ID);
    }

    // 供应商打码
    public Object supplierCode(Map map, String supplier, String ID) {
        if (map.containsKey(supplier)) {
        } else if (supplier.equals("00007011") || supplier.equals("00000286")) {
            map.put(supplier, "巴图鲁");
        } else if ("00006989".equals(supplier) || "00006570".equals(supplier)) {
            map.put(supplier, "三头六臂");
        } else if (supplier.equals("00004465")) { // 现金外采
            String random = "999999";
            map.put(supplier, random);
        } else {
            String numeric = this.getNumeric(supplier);
            // 供应商最后5位数
            String supplierLastFiveNumber = numeric.substring(
                    numeric.length() < 5 ? 0 : numeric.length() - 5);
            // 编码最后3位
            String s = this.getNumeric(ID);
            String IDLastThreeNumber = s.substring(s.length() - 3);
            int random = Integer.valueOf(supplierLastFiveNumber) + Integer.valueOf(IDLastThreeNumber);
            String mosaic;
            if (random < 1000 )
                mosaic = "00" + String.valueOf(random);
            else if (random >= 1000 && random < 10000)
                mosaic = "0" + String.valueOf(random);
            else
                mosaic = String.valueOf(random);
            map.put(supplier, mosaic);
        }
        return map.get(supplier);
    }
    // 获取真实的供应商

    public Object getRealSupplier(Map map, String supplier, String ID) {
        if (map.containsKey(supplier)) {
        } else if (supplier.equals("00007011") || supplier.equals("00000286")) {
            map.put(supplier, "巴图鲁");
        } else if ("00006989".equals(supplier) || "00006570".equals(supplier)) {
            map.put(supplier, "三头六臂");
        } else if (supplier.equals("00004465")) {// 现金外采
            String random = "999999";
            map.put(supplier, random);
        } else if (!map.containsKey(supplier)) {
            PartyRole supplierPartyRole = SpringManager.getBean(PartyRoleRepository.class).findOne(supplier.substring(2));
            if (supplierPartyRole == null) supplierPartyRole = SpringManager.getBean(PartyRoleRepository.class).findOne(supplier);
            Party party = supplierPartyRole.getParty() ;
            String name = party != null ? (party.getAbbreviation() != null ? party.getAbbreviation() : party.getName()) : "";
            map.put(supplier, name);
        }
        return map.get(supplier);
    }
    /**
     * 从字符串中提取纯数字
     * @param str
     * @return
     */
    public String getNumeric(String str) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 构建询价池请求参数
     */
    public JSONObject buildInquiryPoolRequestParam(JSONObject jo) {
        JSONObject condition = new JSONObject();
        String deptId = "";
        String id = jo.getString("id");
        String orderType = jo.getString("orderTypeTemp");
        if (id == null&&orderType==null) throw new RuntimeException("单号不允许为空");
        try {
            if ("ServicePlan".equals(jo.getString("innerBusinessType"))||"服务方案1".equals(orderType) || "服务方案".equals(orderType)) {
                condition.put("CJHM", jo.getJSONObject("fnCustomerExpandTemp").getString("vin"));
                deptId = jo.getJSONObject("serviceDept").getString("id");
            } else {
                condition.put("CJHM", jo.getJSONObject("customerCar").getString("vin"));
                deptId = jo.getJSONObject("fixedLossDept").getString("id");
                if (jo.getJSONObject("orderType")!=null&&"B".equals(jo.getJSONObject("orderType").getString("code")))
                    deptId = jo.getJSONObject("getCarDept").getString("id");
            }
        }catch (Exception e){
            throw new RuntimeException("门店获取失败,请检查是否门店角色");
        }
        Dept dept = SpringManager.getBean(DeptRepository.class).findOne(deptId);
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false,true, dept);
        condition.put("MDID", dept.getOrigin());
        condition.put("PTID", platform.getId());
        List<Map> maps = SpringManager.getBean(PurchasingGroupRepository.class).accordingToDeptGetPurchasingGroup(deptId);
        if (maps== null || maps.size() == 0)
            throw new RuntimeException("当前部门未设置采购组，请联系中转站维护！");
        condition.put("CGZ", maps);
        condition.put("PLAN", jo.getString("plan"));
        return condition;
    }
}
